import React, { memo, useState } from "react";
import type { ReactNode, FC } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
import { message } from "antd";
interface IProps {
  children?: ReactNode;
}
const Register: FC<IProps> = () => {
  const [inputs, setInputs] = useState({
    username: "",
    email: "",
    password: ""
  });
  const [err, setError] = useState(null);

  const navigate = useNavigate();

  const handleChange = (e: any) => {
    setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async () => {
    // e.preventDefault();
    // try {
    //   await axios.post("/blog/auth/register", inputs);
    //   navigate("/login");
    // } catch (err) {
    //   setError(err.response.data);
    // }
    axios
      .post("/users", {
        username: inputs.username,
        password: inputs.password
      })
      .then((res: any) => {
        if (res.status === 201) {
          message.success("注册成功,2s后将跳转到登录页！");
          setTimeout(() => {
            navigate("/login");
          }, 2000);
        } else {
          message.error("注册失败");
        }
      });
  };

  return (
    <div className="auth">
      <h1>Register</h1>
      <form>
        <input
          required
          type="text"
          placeholder="username"
          name="username"
          onChange={handleChange}
        />
        <input required type="email" placeholder="email" name="email" onChange={handleChange} />
        <input
          required
          type="password"
          placeholder="password"
          name="password"
          onChange={handleChange}
        />
        <button onClick={handleSubmit}>Register</button>
        {err && <p>{err}</p>}
        <span>
          Do you have an account? <Link to="/login">Login</Link>
        </span>
      </form>
    </div>
  );
};
export default memo(Register);
